#include "display_common.h"

#define WIN_WIDTH	512
#define WIN_HEIGHT	512

#define CLIP_WIDTH  (WIN_WIDTH << 2)
#define CLIP_HEIGHT (WIN_HEIGHT << 2)

#define WZY_USE_CONFIG

void test(VADisplay va_dpy){
	VADriverContextP testCtx = CTX(va_dpy);
	struct i965_driver_data *i965 = i965_driver_data(testCtx);
	struct intel_batchbuffer *batch = i965->batch;
	printf("flag in batch is : %d. \n", batch->flag);
}

int main(int argc, char **argv)
{

#ifdef WZY_USE_CONFIG
	VAConfigAttrib attrib;

	VAConfigID config_id;

	VAContextID context_id;

	VASurfaceID in_surface_id;
#endif

	VASurfaceID surface_id;

	int major_ver, minor_ver;

	Display *x11_display;

	VADisplay va_dpy;

	VAStatus va_status;

	VADriverContextP ctx;

	Window win;

	int count = 3;
fprintf(stdout, "\n\nNew execution. \n");
fprintf(stderr, "\n\nNew execution. \n");
	if (argc > 1)
		count = atoi(argv[1]);

	x11_display = XOpenDisplay(":0.0");

	if (x11_display == NULL)
	{
		fprintf(stderr, "Can't connect X server!\n");
		exit(-1);
	}

	assert(x11_display);

	va_dpy = vaGetDisplay(x11_display);
	//printf("after GetDisplay\n");
//test(va_dpy);
	va_status = vaInitialize(va_dpy, &major_ver, &minor_ver);
	//printf("after Initialize\n");
//test(va_dpy);
	assert(va_status == VA_STATUS_SUCCESS);

#ifdef WZY_USE_CONFIG
	va_status = vaCreateConfig(va_dpy, VAProfileMPEG2Main, VAEntrypointVLD, &attrib, 1, &config_id);
	CHECK_VASTATUS(va_status, "vaQueryConfigEntrypoints");

	va_status = vaCreateSurfaces(va_dpy, CLIP_WIDTH, CLIP_HEIGHT,
								 VA_RT_FORMAT_YUV420, 1, &in_surface_id);
	CHECK_VASTATUS(va_status, "vaCreateSurfaces");

	// Create a context for this decode pipe
	va_status = vaCreateContext(va_dpy, config_id,
								CLIP_WIDTH,
								((CLIP_HEIGHT + 15) / 16) * 16,
								VA_PROGRESSIVE, &in_surface_id, 1, &context_id);
	CHECK_VASTATUS(va_status, "vaCreateContext");
#endif

	win = XCreateSimpleWindow(x11_display, RootWindow(x11_display, 0), 0, 0,
							  WIN_WIDTH, WIN_HEIGHT, 0, 0, WhitePixel(x11_display, 0));
	XMapWindow(x11_display, win);

	ctx = CTX(va_dpy);
	display_init(ctx);

	surface_id = setup_pipeline(ctx, CLIP_WIDTH, CLIP_HEIGHT);

	while (count)
	{
		printf("%d\n", count);
		va_status = vaPutSurface(va_dpy, surface_id, win,
								 0, 0, CLIP_WIDTH, CLIP_HEIGHT,
								 0, 0, WIN_WIDTH, WIN_HEIGHT, NULL, 0, 0);
		CHECK_VASTATUS(va_status, "vaPutSurface");
		sleep(1);
		count--;
	}

	printf("Finish\n");

#ifdef WZY_USE_CONFIG
	vaDestroySurfaces(va_dpy, &in_surface_id, 1);
	vaDestroyConfig(va_dpy, config_id);
	vaDestroyContext(va_dpy, context_id);
#endif

	display_terminate(ctx, &surface_id);
	vaTerminate(va_dpy);
	XCloseDisplay(x11_display);

	return 0;
}
